package interfaz2;

import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;

/**
 * This class was made to encapsulate certain code and make
 * SubscriptionComposite cleaner. This class just contains a MultiViewComposite
 * and a Browser, inside the MultiViewComposite (it is expected) will be added
 * PostViews of every Post in Dust (that means each Post of each Blog).
 * 
 * @author ole
 */
public class MVCBrowserComposite extends DustComposite {
	private Browser browser;
	private MultiViewComposite posts_view;

	/**
	 * Class constructor.
	 * 
	 * @param parent
	 * 		The parent Composite of this Composite.
	 * @param style:
	 * 		The SWT style bits for a Composite.
	 */
	public MVCBrowserComposite(Composite parent, int style) {
		super(parent, style);
		
		GridData grid;
		
		this.setLayout(new GridLayout());
		
	    // The MultiViewComposite for showing PostViews.
		posts_view = new MultiViewComposite(this, SWT.BORDER);
		grid = new GridData(SWT.FILL, SWT.FILL, true, false);
	    posts_view.setLayoutData(grid);
		
	    // The Browser for show Post contents.
		browser = new Browser(this, SWT.NONE);
		grid = new GridData(GridData.FILL, GridData.FILL, true, true);
	    browser.setLayoutData(grid);
	}
	
	/**
	 * Method that shows the index-th PostView of the MultiViewComposite and
	 * show its content inside the Browser.
	 *
	 * @param index:
	 * 		The index of the PostView to be shown.
	 */
	public void changeView(int index) {
		PostView view;
		Control control;
		
		// Check limits.
		if (index < 0 || index >= posts_view.getChildren().length)
			throw new IndexOutOfBoundsException("Asked to show a PostView " +
												"out of bounds.");
	
		// Change the MultiViewComposite view to the index-th one.
		posts_view.changeView(index);
		control = posts_view.getChildren()[index];
		if (!(control instanceof PostView))
			throw new RuntimeException("Asked to show the PostView of " +
									   "something that isn't a PostView.");
		
		// Set the Browser text to the Post content.
		view = (PostView)control;
		browser.setText(view.getPost().getContent());
		
		// Draw the changes.
		this.layout();
	}
	
	/**
	 * Returns the Browser this MVCBrowserComposite is maintaining.
	 * 
	 * @return:
	 * 		The Browser of this instance.
	 */
	public Browser getBrowser() {
		return browser;
	}

	/**
	 * Returns the MultiViewComposite maintained by this instance.
	 * 
	 * @return:
	 * 		The MultiViewComposite of this instance.
	 */
	public MultiViewComposite getMVC() {
		return posts_view;
	}
}
